package top.broncho.anpods.permission


import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.provider.Settings
import androidx.annotation.MainThread
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import top.broncho.anpods.BuildConfig
import kotlin.coroutines.resume
import kotlin.coroutines.suspendCoroutine


suspend inline fun AppCompatActivity.requestDrawOverlays() =
    suspendCoroutine<Boolean> { continuation ->
        if (Settings.canDrawOverlays(applicationContext)) {
            continuation.resume(true)
            return@suspendCoroutine
        }
        ActionFragment.doAction(this) {
            continuation.resume(it)
        }
    }

suspend inline fun Fragment.requestDrawOverlays() =
    suspendCoroutine<Boolean> { continuation ->
        if (Settings.canDrawOverlays(requireContext())) {
            continuation.resume(true)
            return@suspendCoroutine
        }
        ActionFragment.doAction(this) {
            continuation.resume(it)
        }
    }


class ActionFragment : Fragment() {
    private var resultCallback: ((Boolean) -> Unit)? = null
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        retainInstance = true
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        when (requestCode) {
            PERMISSIONS_REQUEST_CODE ->
                onPermissionResult(Settings.canDrawOverlays(requireContext()))
        }
    }

    fun requestDrawOverlays(resultCallback: (Boolean) -> Unit) {
        this.resultCallback = resultCallback

        startActivityForResult(Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION).apply {
            data = Uri.parse("package:${BuildConfig.APPLICATION_ID}")
        }, PERMISSIONS_REQUEST_CODE)
    }

    private fun onPermissionResult(permissionResult: Boolean) {
        resultCallback?.invoke(permissionResult)

    }

    override fun onAttach(context: Context) {
        super.onAttach(context)
        resultCallback = null
    }

    override fun onDestroy() {
        super.onDestroy()
        resultCallback = null
    }

    companion object {

        private const val TAG = "DrawOverlaysManager"
        private const val PERMISSIONS_REQUEST_CODE = 42

        @JvmStatic
        @MainThread
        fun doAction(
            activity: AppCompatActivity,
            resultCallback: (Boolean) -> Unit
        ) {
            getActionFragment(activity.supportFragmentManager).apply {
                requestDrawOverlays(resultCallback)
            }
        }

        @JvmStatic
        @MainThread
        fun doAction(
            fragment: Fragment,
            resultCallback: (Boolean) -> Unit
        ) {
            getActionFragment(fragment.childFragmentManager).apply {
                requestDrawOverlays(resultCallback)
            }
        }

        private fun getActionFragment(fragmentManager: FragmentManager): ActionFragment {
            var fragment = fragmentManager.findFragmentByTag(TAG)
            if (fragment != null) {
                fragment = fragment as ActionFragment
            } else {
                fragment = ActionFragment()
                fragmentManager.beginTransaction().add(fragment, TAG).commitNow()
            }
            return fragment
        }

    }

}